﻿using MediatR;
using Microsoft.EntityFrameworkCore;
using Process.API.Application.Command.Show;
using Process.Domain;
using Process.ErrorCode;
using Process.Infrastructure.Interface;

namespace Process.API.Application.Handler.Show
{
    public class ReportHandler:IRequestHandler<ReportCommand,APIResult<APIPaging<List<ReportTable>>>>
    {
        IBaseRepository<ReportTable> repRep;

        public ReportHandler(IBaseRepository<ReportTable> repRep)
        {
            this.repRep = repRep;
        }

        public async Task<APIResult<APIPaging<List<ReportTable>>>> Handle(ReportCommand request, CancellationToken cancellationToken)
        {
            var m=await repRep.GetAll().Where(a=>!a.IsDel).ToListAsync();

            if (!string.IsNullOrEmpty(request.DispatchCode))
            {
                m=m.Where(a=>a.DispatchCode.Contains(request.DispatchCode)).ToList();
            }
            if (!string.IsNullOrEmpty(request.DispatchName))
            {
                m=m.Where(a=>a.DispatchName.Contains(request.DispatchName)).ToList();
            }
            if (!string.IsNullOrEmpty(request.ProductionOrdersCode))
            {
                m=m.Where(a=>a.ProductionOrdersCode.Contains(request.ProductionOrdersCode)).ToList();
            }
            if (!string.IsNullOrEmpty(request.ProductionOrdersName))
            {
                m=m.Where(a=>a.ProductionOrdersName.Contains(request.ProductionOrdersName)).ToList();
            }
            if (!string.IsNullOrEmpty(request.ReportingStaff))
            {
                m=m.Where(a=>a.ReportingStaff.Contains(request.ReportingStaff)).ToList();
            }
            if (request.State!=null)
            {
                m=m.Where(a=>a.State==request.State).ToList();
            }


            int count=m.Count();
            int pount = (int)Math.Ceiling(count * 1.0 / request.PageSize);
            m=m.OrderByDescending(a=>a.ReportId).Skip((request.PageIndex-1)*request.PageSize).Take(request.PageSize).ToList();



            return new APIResult<APIPaging<List<ReportTable>>>
            {
                Code = APIEnum.Ok,
                Message = "显示成功",
                Data = new APIPaging<List<ReportTable>>
                {
                    TotalCount = count,
                    TotalPage = pount,
                    PageDatas=m
                }
            };

        }



    }
}
